
import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入 子组件
const Login = () => import(/* webpackChunkName:"login_home_welcome" */ '../components/Login.vue') // 登录组件
const Home = () => import(/* webpackChunkName:"login_home_welcome" */ '../components/Home.vue')// 首页组件
const Welcome = () => import(/* webpackChunkName:"login_home_welcome" */ '../components/Welcome.vue')// 欢迎 组件
const Users = () => import(/* webpackChunkName:"user" */ '../components/users/Users.vue')// 用户组件
const Rights = () => import(/* webpackChunkName:"power" */ '../components/power/Rights.vue') // 权限组件
const Roles = () => import(/* webpackChunkName:"power" */ '../components/power/Roles.vue')// 角色组件
const Cate = () => import(/* webpackChunkName:"goods" */ '../components/goods/Cate.vue')// 商品分类组件
const Params = () => import(/* webpackChunkName:"goods" */ '../components/goods/Params.vue')// 商品分类参数组件
const GoodList = () => import(/* webpackChunkName:"goods" */ '../components/goods/List.vue')// 商品列表组件
const GoodAdd = () => import(/* webpackChunkName:"goods" */ '../components/goods/Add.vue') // 添加商品组件
const Order = () => import(/* webpackChunkName:"order" */ '../components/order/List.vue') // 添加订单列表组件
const Report = () => import(/* webpackChunkName:"report" */ '../components/report/Report.vue') // 添加订单列表组件

Vue.use(VueRouter)

// 创建路由规则数组
const routes = [
  // 将 根路径 重定向到 登录url
  { path: '/', redirect: '/login' },
  // 注册 登录子组件 路由规则
  { path: '/login', component: Login },
  // 注册 主页组件 路由规则
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    // 主页组件的 子路由规则
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodList },
      { path: '/goods/add', component: GoodAdd },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ]
  }
]

// 创建 路由管理器 对象，并传入 路由规则数组
const router = new VueRouter({
  routes
})

// 注册路由守卫，在 路由管理器 根据url找 子组件之前 运行
// eg:http://127.0.0.1:8080#/home   -> to.path 就是 #后面的 /home
router.beforeEach((to, from, next) => {
  // next() 根据当前 url 找 子组件
  if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  // next(新url) 根据 新url 找子组件
  if (!tokenStr) return next('login') // 修改 了 url地址，变成了：http://127.0.0.1:8080#/login
  next()
})

// 导出路由管理器
export default router
